<?php

class Db_Locale_Translations extends Common {
	protected static $tableName = TAB_TRANSLATIONS;
	protected static $dbFields = array(
		'id',
		't_lang_id',
		't_module',
		't_key',
		't_content',
		't_is_html',
		't_is_path',
		'deleted'
	);
	public $objectArray;
	public $id;
	public $t_lang_id;
	public $t_module;
	public $t_key;
	public $t_content;
	public $t_is_html;
	public $t_is_path;
	public $deleted;

	public static $t = array(); // Current project translations.
	public static $ct = array(); // Country based translations. Filled only for the admin project.
	public static $toTranslate = array(); // List of used modules and keys which are not yet translated. Used for inline translations.
	public static $cToTranslate = array(); // The same as $toTranslate. Used for inline translations in the admin panel.

	function __construct($value=NULL, $fieldName=NULL) {
		parent::__construct($value, $fieldName);
	}

	public static function loadTrans($langId, $countryBased = false) {
		if ($countryBased) {
			$t =& self::$ct;
		} else {
			$t =& self::$t;
		}
		$sql = "SELECT * FROM ?f WHERE `t_lang_id`=?i AND `deleted`=0;";
		$result = self::$DB->q($sql, self::$tableName, $langId);
		while($trans = $result->fetch_assoc()) {
			if (!empty($trans['t_key'])) {
				if (!isset($t[$trans['t_module']])) {
					$t[$trans['t_module']] = array();
				}
				$t[$trans['t_module']][$trans['t_key']] = $trans['t_content'];
			} else {
				$t[$trans['t_module']] = $trans['t_content'];
			}
		}
	}

	public static function processTranslations($formData = array()) {
		if (is_array($formData) && count($formData) > 0) {
			$thisOjb = new self();
			$langs = conf('LANGS_ID');
			foreach ($formData as $lang => $modules) {
				foreach ($modules as $module => $data) {
					if (is_array($data)) {
						foreach ($data as $key => $content) {
							if (!empty($content)) {
								$thisOjb->id = NULL;
								$thisOjb->t_lang_id = $langs[$lang];
								$thisOjb->t_module = $module;
								$thisOjb->t_key = $key;
								$thisOjb->t_content = $content;
								$thisOjb->save();
							}
						}
					} else {
						if (!empty($data)) {
							$thisOjb->id = NULL;
							$thisOjb->t_lang_id = $langs[$lang];
							$thisOjb->t_module = $module;
							$thisOjb->t_key = NULL;
							$thisOjb->t_content = $data;
							$thisOjb->save();
						}
					}
				}
			}
			return true;
		} else {
			return false;
		}
	}

	/**
	 * @static
	 * @param $args array (1 - $module, 2 - $key, 3 - comma separated values)
	 * @return mixed
	 */
	public static function t($args = array()) {
        $module = array_shift ($args);
        $key = array_shift ($args);

		$result = NULL;
		if (empty($key)) {
			if (isset(self::$t[$module])) {
				$result = self::$t[$module];
			} else {
				$result = $module;
				self::$toTranslate[$module] = '';
			}
		} else {
			if (isset(self::$t[$module][$key])) {
				$result = self::$t[$module][$key];
			} else {
				$result = $module.'_'.$key;
				Db_Locale_Untranslated::setUntranslated($module, $key);
				self::$toTranslate[$module][$key] = '';
			}
		}

		return (count($args) > 0) ? vsprintf($result, $args) : $result;
	}

	/**
	 * This function should only be used in the ADMIN projects when displaying translations from other projects.
	 * Ex. the grid with all the products (title, description, etc.)
	 *
	 * @static
	 * @param $args array (1 - $module, 2 - $key, 3 - comma separated values)
	 * @return mixed
	 */
	public static function ct($args = array()) {
        $module = array_shift ($args);
        $key = array_shift ($args);

		$result = NULL;
		if (empty($key)) {
			if (isset(self::$ct[$module])) {
				$result = self::$ct[$module];
			} else {
				$result = $module;
				self::$cToTranslate[$module] = '';
			}
		} else {
			if (isset(self::$ct[$module][$key])) {
				$result = self::$ct[$module][$key];
			} else {
				$result = $module.'_'.$key;
				Db_Locale_Untranslated::setUntranslated($module, $key);
				self::$cToTranslate[$module][$key] = '';
			}
		}

		return (count($args) > 0) ? vsprintf($result, $args) : $result;
	}

    public static function isPath($translationId) {
        $sql = "SELECT `t_is_path` FROM ?f WHERE ?f=?i AND ?f=0;";
        $isPath = self::$DB->selectCell($sql, self::$tableName, 'id', $translationId, 'deleted');
        if($isPath > 0){
            return true;
        } else {
            return false;
        }
    }

	public static function loadAllTrans($limit, $searchSql = '', $orderBy = '') {
		if (empty($searchSql)) {
			$searchSql = '1=1';
		}
		if (empty($orderBy)) {
			$orderBy = ' ORDER BY `t_module` ASC, `t_key` ASC ';
		}
		$orderBy .= ', `t_lang_id` ASC';

		$having = '';
		if (post('showUntranslated', 'int')) {
			$totalLanguages = Db_Locale_Languages::countAll();
			$having="HAVING COUNT(`t_content`) < {$totalLanguages}";
		}
		$sql = "SELECT `l`.`id` AS lang_id, `tl`.`tl_key` AS `the_key`, `tl`.`tl_module` AS `the_module`, `t`.`id` AS `t_id`,
				`t`.`t_content` AS `content`, `t`.`t_is_html` AS `is_html`, `t`.`t_is_path` AS `is_path` FROM ?f l
				INNER JOIN ( SELECT `t_module` AS `tl_module`, `t_key` AS `tl_key` FROM ?f
							WHERE {$searchSql} AND `deleted` = 0 GROUP BY `t_module`, `t_key` {$having} {$orderBy} {$limit}
					) AS `tl` ON 1=1
				LEFT JOIN ?f t ON `t`.`t_module` = `tl`.`tl_module` AND `tl`.`tl_key` = `t`.`t_key` AND `t`.`deleted`=0 AND `t`.`t_lang_id` = `l`.`id`
				WHERE `l`.`deleted` = 0 {$orderBy};";
		$result = self::$DB->q($sql, TAB_LANGUAGES, self::$tableName, self::$tableName);
		$finalTranslationsArray = array();
		while($translations = $result->fetch_assoc()) {
			$finalTranslationsArray[$translations['the_module']][$translations['the_key']][$translations['lang_id']] = array(
				'id' => $translations['t_id'],
				'content' => $translations['content'],
				'is_html' => (null == $translations['is_html']) ? false : $translations['is_html'],
				'is_path' => $translations['is_path']
			);
		}
		return $finalTranslationsArray;
	}

	public static function deleteByModuleKey($module, $key) {
		self::$DB->q("DELETE FROM ?f WHERE `t_module` = ? AND `t_key` = ? ;", self::$tableName, $module, $key);
		return self::$DB->affectedRows() ? true : false;
	}

    public static function deleteAbstractByModuleKey($module, $key){
        self::$DB->q("UPDATE ?f SET `deleted` = 1 WHERE `t_module` = ? AND `t_key` = ? ", self::$tableName, $module, $key);
        return self::$DB->affectedRows() ? true : false;
    }

	public static function getTotalElements($sqlCondition = '1=1') {
		if (empty($sqlCondition)) {
			$sqlCondition = '1=1';
		}
		$having = '';
		if (post('showUntranslated', 'int')) {
			//TODO: get rid of this count query, try including it in a subquery
			$totalLanguages = Db_Locale_Languages::countAll();
			$having="HAVING COUNT(`t_content`) < {$totalLanguages}";
		}
		return self::$DB->selectCell("SELECT COUNT(*) FROM (SELECT `t_content`, `t_module`, `t_key` FROM ?f WHERE {$sqlCondition} AND `deleted` = 0 GROUP BY `t_module`, `t_key` {$having}) AS `t`", self::$tableName);
	}

	public static function getAllModules() {
		return self::$DB->selectCol("SELECT DISTINCT `t_module` FROM ?f WHERE `deleted` = 0;", self::$tableName);
	}

	/**
	 * @static
	 * @return mixed
	 */
	public static function getHtmlTranslations() {
		return self::$DB->select("SELECT t_module FROM ?f WHERE t_is_html = 1 AND deleted = 0 GROUP BY t_module",self::$tableName);
	}

	public static function getTranslationsKeysByModule($module, $isHtml = false) {
		if (!$module) {
			return false;
		}
		$sqlAdd = '';
		if ($isHtml) {
			$sqlAdd = " AND t_is_html = 1";
		}
		$result =  self::$DB->q("SELECT t_key FROM ?f WHERE t_module = ? {$sqlAdd} AND deleted = 0 GROUP BY t_key", self::$tableName, $module);
		$dataReturn = array();
		while ($data = $result->fetch_object()) {
			$dataReturn[] = $data->t_key;
		}
		return $dataReturn;
	}

    public static function getHtmlTranslationByModuleAndKey($module, $key) {
        $sql = 'SELECT * FROM ?f WHERE `t_module` = ? AND `t_key` = ? AND `deleted` = 0;';
        $allTranslation =  self::$DB->q($sql, self::$tableName, $module, $key);
        $translations = array();

        while ($data = $allTranslation->fetch_assoc()) {
            $translations['t_module'] = $data['t_module'];
            $translations['t_key'] = $data['t_key'];
            $translations['t_content'][$data['t_lang_id']] = $data['t_content'];
            $translations['t_is_html'] = $data['t_is_html'];
            $translations['t_is_path'] = $data['t_is_path'];
            $translations['id'][$data['t_lang_id']] = $data['id'];
        }
        return $translations;
    }

	public static function getContentTranslationByLangKeyModule($langId, $key, $module) {
		$sql = 'SELECT `t_content` FROM ?f WHERE `t_lang_id` = ? AND `t_key` = ? AND `t_module` = ? AND `deleted` = 0;';
		$contentTranslation =  self::$DB->selectCell($sql, self::$tableName, $langId, $key, $module);
		return $contentTranslation;
	}

    /**
     * @static
     * @param $module
     * @param $key
     * @param $value
     * @return bool
     */
    public static function setHtmlTranslation($module, $key, $value) {
        $sql = 'UPDATE ?f SET `t_is_html` = ? WHERE `t_module` = ? AND `t_key` = ? AND `deleted` = 0';
        self::$DB->q($sql, self::$tableName, $value, $module, $key);

        return (self::$DB->affectedRows() ? true : false );
    }

	public static function getTranslationIdByModuleAndKey($module, $key) {
		$sql = "SELECT id FROM ?f WHERE deleted = 0 AND t_module = ? AND t_key = ?";
		$result = self::$DB->q($sql, self::$tableName, $module, $key);
		$resultData = array();
		while($data = $result->fetch_object()) {
			$resultData[] = $data->id;
		}
		return $resultData;
	}

}
